package me.ivenapp.gomoku.component;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.app.Context;

/**
 * 栅格布局
 * 参考：折叠屏适配规范 https://developer.huawei.com/consumer/cn/doc/other/90101#h2-1-1-
 */
public class GridLayout {
    private final Context mContext;
    private static int LEVEL_1;
    private static int LEVEL_2;
    private static int LEVEL_3;

    public GridLayout(Context context) {
        mContext = context;
        LEVEL_1 = AttrHelper.vp2px(320, context);
        LEVEL_2 = AttrHelper.vp2px(600, context);
        LEVEL_3 = AttrHelper.vp2px(840, context);
    }

    /**
     * 创建栅格布局配置信息
     * @param width
     * @param padding 边距
     * @param gutter 栅格间距
     * @return
     */
    public GridLayoutConfig createGridLayoutConfig(int width, int padding, int gutter) {
        GridLayoutConfig config = new GridLayoutConfig();
        config.width = width;
        config.padding = padding;
        config.gutter = gutter;

        if(width < LEVEL_1) {
            config.columns = 2;
        } else if(width < LEVEL_2) {
            config.columns = 4;
        } else if(width < LEVEL_3) {
            config.columns = 8;
        } else  {
            config.columns = 12;
        }

        config.columnWidth = (width - padding * 2 - gutter * (config.columns - 1)) / config.columns;
        //根据设计规范，总列数在[8, 12）的只使用6列来布局
        if(config.columns >= 12) {
            config.contentColumns = 8;
        } else if(config.columns >= 8) {
            config.contentColumns = 6;
        } else {
            config.contentColumns = config.columns;
        }

        config.contentWidth = config.columnWidth * config.contentColumns + gutter * (config.columns - 1);

        return config;
    }

    /**
     * 给组件运用栅格布局
     * @param component 使用栅格布局的组件
     * @param config 配置信息
     */
    public void setLayoutConfig(Component component, GridLayoutConfig config) {
        if(component != null) {
            if(config.contentColumns == config.columns) {
                component.setWidth(config.contentWidth + config.padding * 2);
                component.setHorizontalPadding(config.padding, config.padding);
            } else{
                component.setHorizontalPadding(0, 0);
                component.setWidth(config.contentWidth);
            }
        }
    }

    /**
     * 栅格布局配置信息
     */
    public static class GridLayoutConfig {
        /**
         * 视窗宽度
         */
        public int width;
        public int padding;
        /**
         * 栅格间隔
         */
        public int gutter;
        /**
         * 视窗总栅格数
         */
        public int columns;
        /**
         * 栅格宽度
         */
        public int columnWidth;
        /**
         * 内容宽度。不包括padding
         */
        public int contentWidth;
        /**
         * 内容区占用栅格数
         */
        public int contentColumns;
    }
}
